package huyaoying.study.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

/**
 * 应用NIO来实现文件的复制功能
 *
 * @author huyaoying
 * @date 2022/2/8
 */
public class ChannelDemo {
    public static void main(String[] args) throws IOException {
        String relativelyPath = System.getProperty("user.dir");
        FileInputStream input = new FileInputStream(relativelyPath + "/src/main/resources/testin.txt");
        ReadableByteChannel source = input.getChannel();
        FileOutputStream output = new FileOutputStream(relativelyPath + "/src/main/resources/testout.txt");
        WritableByteChannel destination = output.getChannel();
        copyData(source, destination);
        source.close();
        destination.close();
        System.out.println("Copy Data finished.");
    }


    /**
     * 复制数据
     *
     * @param src  读取通道
     * @param dest 输出通道
     * @throws IOException ioexception
     */
    private static void copyData(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
        // buffer 缓冲区
        ByteBuffer buffer = ByteBuffer.allocateDirect(20 * 1024);
        while (src.read(buffer) != -1) {
            // 调用flip()之后，读/写指针position指到缓冲区头部，并且设置了最多只能读出之前写入的数据长度(而不是整个缓存的容量大小)。
            buffer.flip();
            // hasRemaining()方法用于判断当前位置和限制之间是否有任何元素
            while (buffer.hasRemaining()) {
                dest.write(buffer);
            }
            buffer.clear(); // Now the buffer is empty, ready for the filling
        }
    }
}


